import base64

import streamlit as st

from sklearn.tree import DecisionTreeClassifier
import pickle
import numpy as np

# 预测输入的向量，并以markdown格式展示推荐

st.markdown("# 数据预测")
st.sidebar.markdown("# 数据预测")


# 将图片转换成base64格式（在Web上，流应用程序都是通过发送HTML代码来实现的。）
def set_png_as_page_bg(png_file):
    # Encoding the png_file provided to base64
    with open(png_file, 'rb') as f:
        img = f.read()
    b64 = base64.b64encode(img).decode()
    css = f'''
    <style>
    .stApp {{
        background-image: url("data:image/png;base64,{b64}");
        background-size: cover;
    }}
    </style>
    '''
    # Insert the CSS into the application
    st.markdown(css, unsafe_allow_html=True)


set_png_as_page_bg(r"bg.jpg")

# 缓存器装饰器
@st.cache_resource
def get_model():
    with open("enddata_x", "rb") as f:
        X = pickle.load(f)
    with open("enddata_y", 'rb') as f:
        Y = pickle.load(f)
    X = X.T
    Y = Y.T
    Y = Y.reshape(331461)
    print(X.shape)
    print(Y.shape)
    # x1 = np.asarray([30, 40, 54, 65, 74, 88, 10, 54, 21, 64, 51, 24, 20, 54])
    tree = DecisionTreeClassifier(criterion='gini', splitter='best')
    tree.fit(X, Y.astype('int'))
    return tree

# 缓存器装饰器
@st.cache_data
def model_predict(x: np.array) -> np.array:
    return get_model().predict(x.reshape(1, 14))


st.text_input("需要预测的城市的数据", key="city_name")
data_list = st.session_state.city_name.split(" ")


def get_fuggest(aqi):
    aqi = int(aqi)
    if 0 < aqi < 50:
        return {'a': "优", 'b': "没有影响", 'c': "正常活动"}
    elif 51 < aqi < 100:
        return {'a': "良", 'b': "某些较少污染物会影响异常敏感人的健康，绝大部分人可以接收", 'c': "极少数异常敏感人应当减少户外活动"}
    elif 151 < aqi < 200:
        return {'a': "轻度污染", 'b': "异常敏感人群症状加重，健康人群出现刺激症状",
                'c': "对于老人，儿童患有心脏病，呼吸系统疾病的人群应当减少长时间，高强度的户外运动"}
    elif 201 < aqi < 300:
        return {'a': "中度污染", 'b': "影响健康人群的心脏和呼吸系统，异常敏感人群症状加深",
                'c': "对于老人，儿童患有心脏病，呼吸系统疾病的人群要避免长时间，高强度的户外运动，正常人则减少"}
    elif 301 < aqi < 500:
        return {'a': "严重污染", 'b': "健康人运动耐力降低，有明显强烈症状，提前出现某些疾病",
                'c': "对于老人，儿童和病人应当留在室内，一般人群应避免户外运动"}
    else:
        return {'a': "", 'b': "", 'c': ""}


def write_markdown(a, b, c):
    st.markdown(f"""
    | 等级 | 对市民的健康影响状况 | 采取的措施 |
    | ---- | ---- | ---- |
    | {a} | {b}   | {c}  |
    
    """)


try:
    data_list = np.array([float(i) for i in data_list])
    st.write("## 预测结果为: " + str(model_predict(data_list)[0]+30))
    write_markdown(**get_fuggest(model_predict(data_list)[0]))
except Exception as e:
    st.write("请输入预测数据")
    print(e)
